//
//  WBOauthViewController.swift
//  daoge_sineweibo
//
//  Created by 伍禄林 on 16/9/30.
//  Copyright © 2016年 伍禄林. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBOauthViewController: UIViewController, UIWebViewDelegate {
    
    let webView = UIWebView()
    
    override func loadView() {
        super.loadView()
        
        view = webView
        view.backgroundColor = UIColor.white
        webView.scrollView.isScrollEnabled = false
        title = "登陆授权"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", fontSize: 16, target: self, action: #selector(closeVc), isBack: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill))
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(RedirectURI)"
        
        guard let url = URL(string: urlString)
            else {
            return
        }
        
        let request = URLRequest(url: url)
        webView.loadRequest(request)
        
    }

    
    @objc private func closeVc() {
        
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
        
    }
    
    @objc private func autoFill() {
        
        let js = "document.getElementById('userId').value = '13725358161';" +
        "document.getElementById('passwd').value = 'Wll~@560';"
        
        webView.stringByEvaluatingJavaScript(from: js)
        
    }
    
    /// webview代理方法  将要加载某个请求
    ///
    /// - parameter webView:        webView
    /// - parameter request:        加载的请求
    /// - parameter navigationType: 导航类型
    ///
    /// - returns: 是否加载请求
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //
        if request.url?.absoluteString.hasPrefix(RedirectURI) == false {
          return true
        }
        
        if request.url?.query?.hasPrefix("code=") == false {//字符串中没有“code=”
            
            print("取消授权")
            
            closeVc()
            
            return false
        }
        
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""

        print("code=========" + code)
        
        WBNetworkingManager.shared.loadAccessToken(code: code) { (isSuccess) in
            
            if !isSuccess {
                
                SVProgressHUD.showInfo(withStatus: "登陆失败")
                
            }else{
                
                SVProgressHUD.showInfo(withStatus: "登陆成功")
                
                NotificationCenter.default.post(name: NSNotification.Name(rawValue:WBUserLoginSuccessNotification), object: nil)
                
            }
        }
        
        self.closeVc()
        
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
}
